package com.brsya.movie.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.brsya.base.base.BaseLayoutActivity;
import com.brsya.base.base.Contents;
import com.brsya.base.util.AdBlockUtil;
import com.brsya.base.util.LoggerUtil;
import com.brsya.base.util.UiUtil;
import com.brsya.movie.R;
import com.brsya.movie.widget.MySwipeRefreshLayout;
import com.brsya.movie.widget.MyWebView;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;

public class WebPageActivity extends BaseLayoutActivity {
    // 触发返回的宽度
    private static final int widthBack = 100;

    private MyWebView webView;
    private ProgressBar webProgress;
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    // 屏幕宽度
    private int widthPixels;
    private int heightPixels;
    // 防误触阈值
    private float rawXOffset;
    // 按下时X坐标
    private int downX = -1;
    private int downY = -1;
    private LinearLayout llWebBack;
    private LinearLayout llWebAward;

    // -1 左 1 右
    private int direction = 0;
    // 是否手势操作
    private boolean isGesture;

    private ValueAnimator backValueAnimator;
    private ValueAnimator awardValueAnimator;
    private MySwipeRefreshLayout srlDownRefresh;
    private RelativeLayout rootView;
    private LinearLayout llBackHome;
    private RelativeLayout rlWebAdBox;

//    private AdUtilManage adUtilManage;

    private long loadAdTime = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_page);

        // 获取屏幕宽度
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        widthPixels = outMetrics.widthPixels;
        heightPixels = outMetrics.heightPixels;
        rawXOffset = widthPixels / 5f;

        AdBlockUtil.init(this);

        initView();
        initWebView();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(this);
            String packageName = this.getPackageName();
            if (!packageName.equals(processName)) {
                WebView.setDataDirectorySuffix(processName);
            }
        }

        //        AndroidBugWorkaround.assistActivity(this);
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initView() {
        //        UiUtil.setStatusDark(this, false);
        setDarkStatus();
        //        AndroidBugWorkaround.assistActivity(this);


        findViewById(R.id.ll_back_home).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rlWebAdBox = findViewById(R.id.rl_web_ad_box);

        srlDownRefresh = (MySwipeRefreshLayout) findViewById(R.id.srl_down_refresh);
        rootView = findViewById(R.id.root_view);
        llBackHome = findViewById(R.id.ll_back_home);
        webView = findViewById(R.id.web_view);
        webProgress = findViewById(R.id.web_progress);
        srlDownRefresh.setWebView(webView);
        srlDownRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });

        llWebBack = (LinearLayout) findViewById(R.id.ll_web_back);
        llWebAward = (LinearLayout) findViewById(R.id.ll_web_award);


        backValueAnimator = new ValueAnimator()
                .setDuration(100);
        backValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                llWebBack.setTranslationX(value);
            }
        });
        awardValueAnimator = new ValueAnimator()
                .setDuration(100);
        awardValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                llWebAward.setTranslationX(value);
            }
        });

        RelativeLayout rootView = findViewById(R.id.root_view);
        rootView.setPadding(
                rootView.getPaddingTop(),
                rootView.getPaddingTop() + UiUtil.getStatusBarHeight(WebPageActivity.this),
                rootView.getPaddingRight(),
                rootView.getPaddingBottom()
        );


        if (getIntent() != null && getIntent().getBooleanExtra(Contents.INTENT_H5_SHOW_AD, false)) {
//            AdVideoUtilManage.initNewShow(WebPageActivity.this, true, new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
//                        @Override
//                        public void onAdShow() {
//
//                        }
//
//                        @Override
//                        public void onAdVideoBarClick() {
//
//                        }
//
//                        @Override
//                        public void onAdClose() {
//                        }
//
//                        @Override
//                        public void onVideoComplete() {
//                        }
//
//                        @Override
//                        public void onSkippedVideo() {
//                        }
//                    },
//                    new AdVideoUtilManage.AdLoadListener() {
//                        @Override
//                        public void success() {
//
//                        }
//
//                        @Override
//                        public void error() {
//                        }
//                    });

        }
    }


    private void initWebView() {
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                LoggerUtil.e("onJsAlert");
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                LoggerUtil.e("onJsConfirm");
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                LoggerUtil.e("onJsPrompt");
                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    if (title.contains("404") || title.contains("500") || title.contains("Error") || title.contains("找不到网页") || title.contains("网页无法打开")) {
                        setErrorPage(view);// 加载自定义错误页面
                        view.goBack();
                    }
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress < 100) {
                    webProgress.setVisibility(View.VISIBLE);
                    webProgress.setProgress(newProgress);
                } else {
                    webProgress.setVisibility(View.INVISIBLE);
                    if (srlDownRefresh.isRefreshing()) {
                        srlDownRefresh.setRefreshing(false);
                    }

                    if (System.currentTimeMillis() - loadAdTime > Contents.AD_SHOW_TIME) {
                        loadAdTime = System.currentTimeMillis();
//                        if (adUtilManage != null) {
//                            AdUtilManage.destroy(adUtilManage);
//                        }
//                        adUtilManage = AdUtilManage.initShowBanner(WebPageActivity.this, rlWebAdBox, Contents.AD_TT_SDK_WEB_ID, 60);
                    }
                }
            }

            /**            // For Android < 3.0
             //            public void openFileChooser(ValueCallback<Uri> valueCallback) {
             //            }
             //
             //            // For Android  >= 3.0
             //            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType) {
             //            }
             //
             //            //For Android  >= 4.1
             //            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
             //            } */

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            }


            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("test", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                return true;
            }

            /*** 视频播放相关的方法 **/
            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(WebPageActivity.this);
                frameLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @SuppressLint("SourceLockedOrientationActivity")
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view, callback);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//播放时横屏幕，如果需要改变横竖屏，只需该参数就行了
            }

            @SuppressLint("SourceLockedOrientationActivity")
            @Override
            public void onHideCustomView() {
                hideCustomView();
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//不播放时竖屏
            }


        });


        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (request.isForMainFrame()) {//是否是为 main frame创建
                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                    //                    setErrorPage(view);// 加载自定义错误页面
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                int statusCode = errorResponse.getStatusCode();
                //                if (404 == statusCode || 500 == statusCode) {
                //                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                //                    setErrorPage(view);// 加载自定义错误页面
                //                }
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

                //                String url = request.getUrl().toString();
                //
                //                // 判断是否需要过滤
                //                if (ADBlocker.getInstance().matches(url, null, null, null)) {
                //                    LoggerUtil.e("过滤了广告:" + url);
                //                    return new WebResourceResponse(null, null, null);
                //                }
                //                LoggerUtil.e("加载页面:" + url);

                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                LoggerUtil.e("拦截网页1:" + url);
                //
                if (url.indexOf("http") != 0 && url.indexOf("https") != 0 && url.indexOf("ftp") != 0) {
                    //                    LoggerUtil.e(url);
                    //                    setErrorPage(view);
                    return true;
                }
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 不使用loadUrl(url)方法，防止出现页面重定向后goBack()方法失效。
                LoggerUtil.e("拦截网页2:" + url);
                if (url.indexOf("http") != 0 && url.indexOf("https") != 0 && url.indexOf("ftp") != 0) {
                    LoggerUtil.e(url);
                    return true;
                }
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                super.onUnhandledKeyEvent(view, event);
            }


        });


        webView.evaluateJavascript("javascript:JSMethod()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                //此处为 js 返回的结果
            }
        });

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (isFinishing()) {
                    return;
                }
                if (url == null || url.length() == 0) {
                    return;
                }
                Uri uri = Uri.parse(url);
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                new Handler(Looper.getMainLooper()).postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                webView.goBack();
                            }
                        }, 500
                );
            }
        });
        //        webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> GeneralUtil.downloadBySystem(WebPageActivity.this, url));

        loadUrl();


    }

    /**
     * 加载错误页面
     *
     * @param view webView
     */
    private void setErrorPage(WebView view) {
        Toast.makeText(this, "页面加载失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断是否拦截请求
     *
     * @param url 访问的请求
     * @return 是否拦截请求
     */
    private boolean isIntercept(String url) {
        if (url == null) return false;
        try {
            if (url.startsWith("weixin://") || url.startsWith("alipays://") ||
                    url.startsWith("mailto://") || url.startsWith("tel://")
                //其他自定义的scheme
            ) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
            if (url.contains("play.google.com")) {
                String urlStr = url.substring(url.indexOf("link=https://play.google.com/store/apps/details") + 5);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlStr));
                startActivity(intent);
                webView.goBack();
                return true;
            }
        } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
            return false;
        }
        return false;
    }


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(WebPageActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webView.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        // 右划返回,左划前进
        //        gesture(ev);
        return super.dispatchTouchEvent(ev);
    }

    private void gesture(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                // 按下
                downX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                direction = 0;
                isGesture = true;
                //                }
                break;
            case MotionEvent.ACTION_MOVE:
                // 移动
                if (Math.abs(ev.getRawY() - downY) > (heightPixels / 6f)) {
                    isGesture = false;
                    endAnimator();
                    break;
                }
                if (!webView.isScrollCan()) {
                    endAnimator();
                    break;
                }

                //                if (System.currentTimeMillis() - webView.getScrollTime() > 300) {
                //                    isGesture = false;
                //                    break;
                //                }

                if (!isGesture) {
                    break;
                }

                if (ev.getRawX() - downX > 0) {

                    float rawX = ev.getRawX() - downX - rawXOffset;
                    llWebAward.setTranslationX(0);
                    if (direction != 1) {
                        if (llWebBack.getWidth() >= rawX) {
                            llWebBack.setTranslationX(rawX);
                        } else {
                            llWebBack.setTranslationX(llWebBack.getWidth());
                        }
                        direction = -1;
                    }
                } else if (ev.getRawX() - downX < 0) {
                    llWebBack.setTranslationX(0);

                    float rawX = ev.getRawX() - downX + rawXOffset;
                    if (direction != -1) {

                        //                if (webView.canGoForward()) {
                        if (llWebAward.getWidth() >= -(rawX)) {
                            llWebAward.setTranslationX((rawX));
                        } else {
                            llWebAward.setTranslationX(-(llWebAward.getWidth()));
                        }
                        direction = 1;
                        //                }
                    }
                }

                break;
            case MotionEvent.ACTION_UP:
                // 抬起

                endAnimator();
                if (Math.abs(ev.getRawY() - downY) > heightPixels / 6f) {
                    break;
                }
                if (llWebBack.getWidth() - llWebBack.getTranslationX() < (llWebBack.getWidth() / 3f)) {
                    onBackPressed();
                } else if (llWebAward.getWidth() - Math.abs(llWebAward.getTranslationX()) < (llWebAward.getWidth() / 3f) && webView.canGoForward()) {
                    webView.goForward();
                }
                downX = -1;
                direction = 0;
                webView.setScrollCan(false);

                isGesture = false;
                break;
            default:
                break;
        }
    }

    private void endAnimator() {
        if (llWebBack.getTranslationX() != 0) {
            if (!backValueAnimator.isRunning()) {
                backValueAnimator.setFloatValues(llWebBack.getTranslationX(), 0);
                backValueAnimator.start();
            }
        }
        if (llWebAward.getTranslationX() != 0) {
            if (!awardValueAnimator.isRunning()) {
                awardValueAnimator.setFloatValues(llWebAward.getTranslationX(), 0);
                awardValueAnimator.start();
            }
        }
    }

    private void loadUrl() {
        if (getIntent() != null) {
            if (getIntent().getStringExtra(Contents.INTENT_H5_URL) != null) {
                String url = getIntent().getStringExtra(Contents.INTENT_H5_URL);
                webView.loadUrl(url);
                //                try {
                //                    webView.postUrl("https://m.88hd.tv/search/", ("wd=" + URLEncoder.encode("电影", "UTF-8")).getBytes(StandardCharsets.UTF_8));
                //                } catch (UnsupportedEncodingException e) {
                //                    e.printStackTrace();
                //                }
            }
        }
    }

    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    @Override
    protected void onDestroy() {
//        AdUtilManage.destroy(adUtilManage);

        if (backValueAnimator.isRunning()) {
            backValueAnimator.end();
        }
        if (awardValueAnimator.isRunning()) {
            awardValueAnimator.end();
        }


        super.onDestroy();

    }

    @Override
    public void onBackPressed() {
        if (webView.getUrl() == null) {
            finish();
            return;
        }
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }
}